package com.pi.wms.service;

import com.pi.framework.core.repository.IBaseRepository;
import com.pi.framework.core.service.impl.BaseCrudService;
import com.pi.framework.core.util.ConvertUtils;
import com.pi.framework.core.util.StringUtils;
import com.pi.wms.entity.VwaDocWaveSoList;
import com.pi.wms.repository.WaveSoListRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class WaveSoListService extends BaseCrudService<VwaDocWaveSoList, Long>{

	@Autowired
	private WaveSoListRepository repository;
	
	@Override
	protected IBaseRepository<VwaDocWaveSoList,Long> getRepository() {
		return this.repository;
	}
	
	@Override
	protected Predicate toPredicate(Root<VwaDocWaveSoList> root, CriteriaQuery<?> cq, CriteriaBuilder cb, Map<String, ?> query) {
		List<Predicate> list = new ArrayList<Predicate>();

		Boolean enabled = ConvertUtils.convertObjectToBoolean(query.get("enabled"));
		if (enabled) {
			list.add(cb.equal(root.get("enabled"), enabled));
		}
		// q for select2 searching
		String q = (String) query.get("q");
		if (!org.apache.commons.lang3.StringUtils.isBlank(q)) {
			list.add(cb.or(cb.like(root.get("no"), "%" + q + "%"), cb.like(root.get("name"), "%" + q + "%")));
		}

		// no searching
		String wave = (String) query.get("waveid");
		Long waveid=null;
		if (!StringUtils.isNullOrBlank(wave)) {
			waveid=StringUtils.getLongNumber(wave);
			if (waveid!=null){
				list.add(cb.equal(root.get("waveId"), waveid));
			}
		}

		Long[] array = ConvertUtils.convertToLongArray(query.get("excludeIds"));
		if (array != null) {
			List<Long> ids = Arrays.asList(array);
			if (ids != null && ids.size() > 0) {
				if (ids.size() >= 1000) {					
					ids = ids.subList(0, 1000);
				}
				Predicate p = root.in(ids);
				list.add(cb.and(cb.not(p)));
			}
		}
		Predicate[] p = new Predicate[list.size()];
		return cb.and(list.toArray(p));
	}

    public List<VwaDocWaveSoList> findByWaveId(Long waveId){
	    return this.repository.findByWaveId(waveId);
    }
}
